package com.example;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

public class MyActivity extends Activity {

    public List<File> localFiles = Collections.synchronizedList( new ArrayList<File>() );
    public FTPClient ftpClient = new FTPClient();
    private static final String SettingsFile = "settings";

    Properties settings = new Properties();
    private String hostName;
    private String user;
    private String password;
    private String remoteDirectory;
    private String localDirectory;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ReadSettings();

        //ScanFiles();

    }

    private void ReadSettings() {
        FileInputStream fis = null;
        try {
            fis = openFileInput(SettingsFile);
            settings.load(fis);

            this.hostName = settings.getProperty("hostname");
            this.user = settings.getProperty("user");
            this.password = settings.getProperty("pwd");
            this.remoteDirectory = settings.getProperty("remotedir");

            if (this.localDirectory == null) {
                this.localDirectory = getString(R.string.settings_remote_dir_default);
            }


            this.localDirectory = settings.getProperty("localdir");

            if (this.localDirectory == null) {
                this.localDirectory = getString(R.string.settings_local_dir_default);
            }


        } catch (Exception e) {
            Toast.makeText(MyActivity.this, "Local " + e.getMessage(), Toast.LENGTH_LONG).show();

        }


    }

    private void WriteSettings() {
        try {
            FileOutputStream fos = openFileOutput(SettingsFile, Context.MODE_PRIVATE);

            settings.setProperty("hostname", this.hostName);
            settings.setProperty("user", this.user);
            settings.setProperty("pwd", this.password);
            settings.setProperty("remotedir", this.remoteDirectory);
            settings.setProperty("localdir", this.localDirectory);

            settings.store(fos, "");

        } catch (Exception e) {
            Toast.makeText(MyActivity.this, "Local " + e.getMessage(), Toast.LENGTH_LONG).show();

        }
    }

    private void initFtpClient(){

        TextView messageBar = (TextView) findViewById(R.id.messagebar);

        try {

            ftpClient.connect(this.hostName);
            boolean loggedIn = ftpClient.login(this.user, this.password);

            if (!loggedIn) {
                return;
            }

            ftpClient.changeWorkingDirectory(this.remoteDirectory);
            ftpClient.enterLocalPassiveMode();


        } catch (Exception e) {

            messageBar.setText("Got error while connecting: " + e.getMessage());

        }
//        finally {
//            try {
//                ftpClient.disconnect();
//            } catch (IOException e) {
//                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//                messageBar.setText("Got error while disconnecting: " + e.getMessage());
//            }
//        }
    }

    private void ScanFiles() {
//        ListView lv = (ListView) findViewById(R.id.files);
//        lv.setTextFilterEnabled(true);

        this.localFiles.clear();

        TextView messageBar = (TextView) findViewById(R.id.messagebar);
        messageBar.setText("No files");

        GridView uploadFilesView = (GridView) findViewById(R.id.gridview);


        if (!ValidSettings()) {
            return;
        }

        try {

            ftpClient.connect(this.hostName);
            boolean loggedIn = ftpClient.login(this.user, this.password);

            if (!loggedIn) {
                return;
            }

            ftpClient.changeWorkingDirectory(this.remoteDirectory);


            File path = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM + this.localDirectory);

            Toast.makeText(MyActivity.this, "Local " + path.getAbsolutePath(), Toast.LENGTH_LONG).show();

            ftpClient.enterLocalPassiveMode();
            final String[] files = ftpClient.listNames();


            if (files != null && files.length > 0) {

                Collections.addAll(localFiles, path.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {

                        for (String remoteFileName : files) {
                            if (remoteFileName.equals(file.getName())) {
                                return false;
                            }
                        }

                        return true;  //To change body of implemented methods use File | Settings | File Templates.
                    }

                })
                );

                MessageBarTextBuilder textBuilder = new MessageBarTextBuilder(this.localFiles);


                messageBar.setText(textBuilder.buildText());


                uploadFilesView.setAdapter(new ImageAdapter(this.localFiles, this));

            } else {

                messageBar.setText("No files to transfer to " + ftpClient.printWorkingDirectory());

            }

        } catch (Exception e) {

            messageBar.setText("Got error while scanning: " + e.getMessage());

        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                messageBar.setText("Got error while disconnecting: " + e.getMessage());
            }
        }
    }

    private boolean ValidSettings() {
        return this.hostName != null && this.hostName != "" && this.localDirectory != null && this.remoteDirectory != null;
    }

    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            View v = getCurrentFocus();
            Toast.makeText(MyActivity.this, v.getClass().toString(), Toast.LENGTH_SHORT).show();

            return true;
        }

        return false;


    }

    public void onButtonRefreshClicked(View v) {
        //ScanFiles();

        if (!ValidSettings()) {
            return;
        }

        this.initFtpClient();

        ScanFilesTask task = new ScanFilesTask(this.getMainViewHolder(), Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM + this.localDirectory),  this.ftpClient);

        task.execute(this.localFiles);

    }

    public void onButtonClicked(View v) {
        // Do something when the button is clicked

        try {
            ftpClient.connect(this.hostName);
            boolean loggedIn = ftpClient.login(this.user, this.password);

            if (!loggedIn) {
                return;
            }

            ftpClient.changeWorkingDirectory(this.remoteDirectory);
            ftpClient.enterLocalPassiveMode();

        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }



        UploadBackgroundTask uploadBackgroundTask =
                new UploadBackgroundTask(this.getMainViewHolder(), ftpClient);
        uploadBackgroundTask.execute(localFiles);

    }

    private MainViewHolder getMainViewHolder(){

        MainViewHolder holder = new MainViewHolder();
        holder.dataView =  (GridView) findViewById(R.id.gridview);
        holder.messagesView = (TextView) findViewById(R.id.messagebar);

        return holder;
    }

    public void onButtonSettingsClicked(View v) {
        setContentView(R.layout.input);

        EditText editHostName = (EditText) findViewById(R.id.hostname);
        editHostName.setText(this.hostName);

        EditText editUserName = (EditText) findViewById(R.id.user);
        editUserName.setText(this.user);

        EditText editPassword = (EditText) findViewById(R.id.password);
        editPassword.setText(this.password);

        EditText editRemoteDir = (EditText) findViewById(R.id.remote_dir);
        editRemoteDir.setText(this.remoteDirectory);

        EditText editLocalDir = (EditText) findViewById(R.id.local_dir);
        editLocalDir.setText(this.localDirectory);

    }

    public void onButtonDoneClicked(View v) {

        EditText editHostName = (EditText) findViewById(R.id.hostname);
        this.hostName = editHostName.getText().toString().trim();

        EditText editUserName = (EditText) findViewById(R.id.user);
        this.user = editUserName.getText().toString().trim();

        EditText editPassword = (EditText) findViewById(R.id.password);
        this.password = editPassword.getText().toString().trim();

        EditText editRemoteDir = (EditText) findViewById(R.id.remote_dir);
        this.remoteDirectory = editRemoteDir.getText().toString().trim();

        EditText editLocalDir = (EditText) findViewById(R.id.local_dir);
        this.localDirectory = editLocalDir.getText().toString().trim();

        this.WriteSettings();

        setContentView(R.layout.main);
    }

    /**
     *
     public void onButtonClicked(View v) {
     // Do something when the button is clicked



     try {
     ftpClient.connect(this.hostName);
     boolean loggedIn = ftpClient.login(this.user, this.password);

     if (!loggedIn) {
     return;
     }

     ftpClient.changeWorkingDirectory(this.remoteDirectory);
     } catch (IOException e) {
     e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
     }

     ArrayList<File> remainingFiles = new ArrayList<File>();

     for (File file : this.localFiles) {
     FileInputStream fis = null;
     OutputStream out = null;

     try {
     fis = new FileInputStream(file);
     Toast.makeText(MyActivity.this, String.format("Uploading %s", file.getName()), Toast.LENGTH_SHORT).show();
     ftpClient.storeFile(file.getName(), fis);

     //                out =  ftpClient.storeFileStream(file.getName());
     //
     //                byte[] buffer = new byte[1024];
     //                int len;
     //
     //                while ( (len = fis.read(buffer))!= -1){
     //                    out.write(buffer,0,len);
     //                    out.flush();
     //                }

     } catch (IOException e) {
     //Toast.makeText(MyActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
     //To change body of catch statement use File | Settings | File Templates.
     remainingFiles.add(file);
     } finally {
     try {
     if ( fis !=null)
     {
     fis.close();
     }

     if (out !=null ) {
     out.close();
     }
     } catch (IOException e) {
     e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

     }
     }

     }

     try {
     ftpClient.disconnect();
     } catch (IOException e) {
     e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
     }


     localFiles = remainingFiles.toArray(new File[]{});

     GridView uploadFilesView = (GridView) findViewById(R.id.gridview);
     uploadFilesView.setAdapter(new ImageAdapter(localFiles, this));

     //ListView lv = (ListView) findViewById(R.id.files);
     //lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, uploadFileNames));

     }

     * */
}
